package org.custom.spring.boot.datasource.application;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * ApplicationContext 相关工具类
 *
 * @author 李坤
 * @date 2022/4/1 20:06
 */
@Component
public class ApplicationUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 获取给定类型的Spring Bean
     *
     * @param clazz 给定的类型
     * @param <T>   泛型
     *
     * @return 给定类型的Spring Bean
     */
    public static <T> T getBean4Class(Class<T> clazz) {
        return ApplicationUtil.applicationContext.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationUtil.applicationContext = applicationContext;
    }
}
